<template>
    <div class="login_content">
        <h3 class="login_content_title">Vue3-DynamicRouter-template</h3>
        <el-form hide-required-asterisk label-width="50px" ref="ruleFormRef" :model="params" :rules="rules">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="账号" prop="userName">
                        <el-input @keyup.enter.native="keyDown" v-model="params.userName"
                            placeholder="请输入账号～有后台账号校验必须:admin" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="密码" prop="password">
                        <el-input @keyup.enter.native="keyDown" v-model="params.password"
                            placeholder="请输入密码～有后台账号校验必须:1234" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-button type="primary" @click="gotoLogin(ruleFormRef)">登陆</el-button>
        <el-button type="success" @click="Login(ruleFormRef)">游客登录</el-button>
    </div>

</template>

<script lang="ts" setup>
import { useRouter } from "vue-router";
import { GetRouter } from '@/stores/modules/RouterList'
import { getToken } from "@/api/system/user";
import { onMounted, ref } from "vue";
import { ElMessage } from 'element-plus'

const ruleFormRef = ref()
const router = useRouter()
let store = GetRouter();
const params = ref({ userName: null, password: null }) as any
const rules = ref({
    userName: [
        { required: true, message: '请输入账号', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ]
})

const keyDown = (e: any) => {
    gotoLogin(ruleFormRef.value)
}

const gotoLogin = async (formEl: any) => {
    store.DelVisitor()
    if (!formEl) return
    await formEl.validate(async (valid: any, fields: any) => {
        if (valid) {
            const dt: any = await getToken(params.value)
            if (dt.data.success) {
                store.getToken(dt.data.token)
                ElMessage.success(dt.data.message)
                setTimeout(() => {
                    router.push('/')
                    location.reload()
                }, 1000);
            } else ElMessage.error(dt.data.message)
        } else {
            // console.log('error submit!', fields)
        }
    })
}

const Login = () => {
    store.SetVisitor()
    router.push('/')
}
</script>
<style lang="less">
.login_content {
    width: 600px;
    height: 400px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    background-color: #fff;
    padding: 40px;
    box-sizing: border-box;
    border-radius: 10px;

    .login_content_title {
        margin-bottom: 120px;
    }
}
</style>